
// 每次从map场景离开前对map进行截图
export function useMapSnap() {
    const sceneManagerGoto = SceneManager.goto;
    SceneManager.goto = function (sceneClass) {
        if (this._scene && this._scene.constructor.name === 'Scene_Map') {
            let windowLayerVisile = this._scene._windowLayer.visible
            this._scene._windowLayer.visible = false
            this._mapSnap = Bitmap.snap(this._scene)
            this._scene._windowLayer.visible = windowLayerVisile;
        }
        sceneManagerGoto.call(this, sceneClass)
    }
}

export function useSwdaSaveDataStorage() {
    DataManager.maxSavefiles = () => 100

    function getResizeSnapshot(height = Graphics.height / 2, width = Graphics.width / 2) {
        const snapshotBitmap = SceneManager._mapSnap
        const resizedCanvas = document.createElement('canvas')
        const resizedContext = resizedCanvas.getContext('2d')
        resizedCanvas.width = width
        resizedCanvas.height = height
        resizedContext.drawImage(snapshotBitmap.canvas, 0, 0, resizedCanvas.width, resizedCanvas.height)
        const snapshotBase64 = resizedCanvas.toDataURL('image/webp', 0.9)
        return snapshotBase64
    }

    // yep把jsonlength限制取消了，此处采取同样的措施，所以不再继承yep
    DataManager.saveGameWithoutRescue = function (savefileId) {
        const json = JsonEx.stringify(this.makeSaveContents());

        StorageManager.saveSnapshot(savefileId, getResizeSnapshot())
        StorageManager.save(savefileId, json);
        this._lastAccessedId = savefileId;
        let globalInfo = this.loadGlobalInfo() || [];
        globalInfo[savefileId] = this.makeSavefileInfo();
        this.saveGlobalInfo(globalInfo);
        this.saveGlobalEnemyBook();// 老饕：神魔录在这里存入
        return true;
    };

    StorageManager.saveSnapshot = function (savefileId, snapshotBase64) {
        if (savefileId < 1) return;// 全局数据不必快照，只有具体id的存档位才快照

        if (this.isLocalMode()) {
            this.saveToLocalSnapFile(savefileId, snapshotBase64)
        } else {
            this.saveToWebSnapStorage(savefileId, snapshotBase64)
        }
    }

    StorageManager.saveToLocalSnapFile = function (savefileId, snapshotBase64) {
        const fs = require('fs');
        const snapshot = LZString.compressToBase64(snapshotBase64)

        const dirPath = this.localFileDirectoryPath()
        const filePath = this.localFilePath(savefileId)//same as file01.rpgsave
        const snapFilePath = `${filePath}.snap`

        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath);
        }
        fs.writeFileSync(snapFilePath, snapshot) // save snapshot
    }

    // 设置缓存，避免反复取数，在离开window时需要清空
    DataManager.snapShotCache = {}
    DataManager.clearSnapShotCache = function () {
        DataManager.snapShotCache = {}
    }
    DataManager.loadSnapShot = function (index) {
        let cache = DataManager.snapShotCache

        if (cache[index]) {
            return cache[index]
        } else {
            const snapshot = StorageManager.loadSnapShot(index)
            cache[index] = snapshot
            return snapshot
        }
    }
    StorageManager.loadSnapShot = function (savefileId) {
        if (savefileId < 1) return;
        if (this.isLocalMode()) {
            return this.loadLocalSnapFile(savefileId)
        } else {
            return this.loadWebSnapStorage(savefileId)
        }
    }

    StorageManager.loadLocalSnapFile = function (savefileId) {
        let data = null;
        const fs = require('fs');
        const filePath = this.localFilePath(savefileId)
        const snapFilePath = `${filePath}.snap`

        if (fs.existsSync(snapFilePath)) {
            data = fs.readFileSync(snapFilePath, { encoding: 'utf8' });
        }

        return LZString.decompressFromBase64(data);
    }

    Game_Party.prototype.charactersLevelForSavefile = function () {
        return this.battleMembers().map(function (actor) {
            return [actor._actorId, actor._level];
        });
    }

    // 重新设置存档文件的列表的元数据格式（用于记录选择界面）
    DataManager.makeSavefileInfo = function () {
        return {
            globalId: this._globalId, // 全局ID标识
            title: $dataSystem.gameTitle, // 游戏标题
            gold: $gameParty.gold() || 0, // 金钱数额
            mapName: $gameMap.saveName(), // 地图名(默认$gameMap.displayName())
            actors: $gameParty.charactersLevelForSavefile(),// new-设置actor
            playtime: $gameSystem.playtimeText(), // 游戏时长
            timestamp: Date.now(), // 当前时间
        }
    }
}

